package com.yonyou.crm.cum.customer.ctrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.base.doc.rmitf.IBaseDocRmService;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.pub.entity.ObjTypeEnum;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.cum.contact.entity.ContactVO;
import com.yonyou.crm.cum.contact.rmitf.IContactRmService;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.cum.customer.rmitf.ICustomerRelusersRmService;
import com.yonyou.crm.cum.customer.rmitf.IGroupCustomerRmService;
import com.yonyou.crm.cum.customer.rmitf.IGroupCustomerSalesRmService;
import com.yonyou.crm.sprc.lead.rmitf.ILeadRmService;
import com.yonyou.crm.sprc.opportunity.entity.OpportunityVO;
import com.yonyou.crm.sprc.opportunity.rmitf.IOpportunityRmService;
import com.yonyou.crm.sys.dynamic.entity.DynamicVO;
import com.yonyou.crm.sys.modules.rmitf.IBiztypeRmService;
import com.yonyou.crm.sys.queryplan.entity.QueryPlanVO;
import com.yonyou.crm.sys.queryplan.rmitf.IQueryPlanRmSerivice;
import com.yonyou.crm.tpub.attachment.entity.AttachmentVO;
import com.yonyou.crm.tpub.attachment.rmitf.IAttachmentRmService;

@RestController
@RequestMapping(value = "/cum/groupcustomers")
public class GroupCustomerCtrl {

	@Autowired
	private IGroupCustomerRmService service;
	@Autowired
	private IGroupCustomerSalesRmService salesRmService;
	@Autowired
	private IBaseDocRmService baseDocRmService;
	@Autowired
	private ICustomerRelusersRmService relusersRmService;
	@Autowired
	private IContactRmService contactRmService;
	@Autowired
	private IOpportunityRmService opportunityRmService;
	@Autowired
	private ILeadRmService leadRmService;
	@Autowired
	private IBiztypeRmService biztypeService;
	@Autowired
	private IQueryPlanRmSerivice  qpService;
	@Autowired
	private IAttachmentRmService attachService;
	
	/**
	 * 查询模板
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "querytemplate",method = RequestMethod.GET)
	public Object getQueryTemplate(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException{

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("objId", ObjTypeEnum.CUSTOMER.getValue());
		param.put("clientType", 1);
		param.put("menuId", 27);
		List<QueryPlanVO> queryPlanList = qpService.getQueryPlanList(param);
		
		JSONObject result = new JSONObject();
		result.put("plan", queryPlanList);
		
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 获取档案信息和档案详情
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "docs", method = RequestMethod.GET)
	public Object getDocAndDetailList(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("1", "type");// 客户类型
		map.put("2", "cannelType");// 渠道类型
		map.put("3", "source");// 客户来源
		map.put("4", "identityType");// 客户身份
		map.put("5", "level");// 客户等级
		map.put("6", "state");// 客户状态
		Map<String, Object> baseDocMap = baseDocRmService
				.getDocAndDetailList(map);
		JSONObject result = new JSONObject();
		result.put("enumData", baseDocMap);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 获取详情
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}
		CustomerVO customer = service.getDetail(id);
		return ResponseUtil.getObject(customer);
	}

	/**
	 * 获取客户列表（分页）
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(method = RequestMethod.GET)
	public Object getList(HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject paramObject = RequestUtil.getParamObject(request);
		int page = paramObject.getInt("page");
		int pageSize = paramObject.getInt("pageSize");
		
		Map<String, Object> searchMap = (Map<String, Object>) paramObject.get("searchMap");
		if (searchMap == null) {
			searchMap  = new HashMap<String, Object>();
		}
		
		Map<String, Object> searchPlanMap = (Map<String, Object>) paramObject.get("searchPlanMap");
		if (searchPlanMap != null && searchPlanMap.size() > 0) {
			searchMap.put("id", searchPlanMap.get("id"));
			searchMap.put("defClass", searchPlanMap.get("defClass"));
		}
		
		Page<CustomerVO> customerList = service.getList(new Page<CustomerVO>(page, pageSize), searchMap);
		return ResponseUtil.getObject(customerList);
	}

	/**
	 * 集团客户保存
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object save(HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		CustomerVO customer = getCustomerVO(request);
		if (customer == null) {
			throw new CrmMessageException("客户实体转换失败");
		}
		customer = service.insert(customer);
		if (customer.getId() == null) {
			throw new CrmMessageException("获取自增主键失败，未保存成功");
		}
		return ResponseUtil.getObject(customer);
	}

	/**
	 * vo转换
	 * @param request
	 * @return
	 */
	private CustomerVO getCustomerVO(HttpServletRequest request) {
		Map<String, Class<?>> fieldClassMap = new HashMap<String, Class<?>>();
		fieldClassMap.put("salesVOs", CustomerSalesVO.class);
		return RequestUtil.getVO(request, CustomerVO.class, fieldClassMap);
	}

	/**
	 * 检查名称是否存在
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}/checkname", method = RequestMethod.GET)
	public Object checkNameExist(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		String name = paramObject.getString("name");
		CustomerVO customer = new CustomerVO();
		customer.setName(name);
		if (!id.equals(0L)) {
			customer.setId(id);
		}
		int isExist = service.checkNameExist(customer);
		return ResponseUtil.getObject(isExist);
	}

	/**
	 * 集团客户更新
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) {
		CustomerVO customer = getCustomerVO(request);
		customer.setId(id);
		customer = service.update(customer);
		return ResponseUtil.getObject(customer);
	}

	/**
	 * 集团客户删除
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) {
		service.delete(id);
		return ResponseUtil.getObject();
	}

	/**
	 * 集团客户批量删除
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");
		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		String[] idArray = idsStr.split(",");
		if (idArray.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		int page = paramObj.getInt("page");
		int pageSize = paramObj.getInt("pageSize");
		Map<String, Object> paraMap = (Map<String, Object>) paramObj.get("searchMap");
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		Page<CustomerVO> customerPage = service.batchDelete(idArray,new Page<CustomerVO>(page, pageSize), paraMap);
		return ResponseUtil.getObject(customerPage);
	}

	/**
	 * 更新状态
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/state", method = RequestMethod.PUT)
	public Object updateState(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) {
		int enableState = (int) RequestUtil.getObject(request, "enableState");
		service.updateState(id, enableState);
		return ResponseUtil.getObject();
	}

	/**
	 * 批量更新状态
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "state", method = RequestMethod.PUT)
	public Object batchUpdateState(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");
		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		String[] idArray = idsStr.split(",");
		if (idArray.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		Integer enableState = paramObj.getInt("enableState");
		if (enableState == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "停启用状态不能为空");
		}
		int page = paramObj.getInt("page");
		int pageSize = paramObj.getInt("pageSize");
		@SuppressWarnings("unchecked")
		Map<String, Object> paraMap = (Map<String, Object>) paramObj.get("searchMap");
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		Page<CustomerVO> customerPage = service.batchUpdateState(idArray, enableState, new Page<CustomerVO>(page, pageSize), paraMap);
		return ResponseUtil.getObject(customerPage);
	}

	/**
	 * 关注、取消关注
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/follows", method = RequestMethod.PUT)
	public Object followState(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) {
		int followState = (int) RequestUtil.getObject(request, "followState");
		Map<String, Object> map = new HashMap<String, Object>();
		int result = 0;
		if (followState == 0) {
			service.saveFollow(id);
			result = 1;
		} else {
			service.deleteFollow(id);
		}
		map.put("followState", result);
		return ResponseUtil.getObject(map);
	}

	/**
	 * 判断是否已关注
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/isfollow", method = RequestMethod.GET)
	public Object isFollow(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) {
		int isFollow = service.isFollow(id);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("followState", isFollow);
		return ResponseUtil.getObject(map);
	}
	
	/**
	 * 关注人列表
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/followuser", method = RequestMethod.GET)
	public Object followUserList(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		@SuppressWarnings("unchecked")
		Map<String, Object> searchMap = (Map<String, Object>) paramObject
				.get("searchMap");
		if (searchMap == null) {
			searchMap = new HashMap<String, Object>();
		}
		Map<String, Object> list = service.getFollowUserList(id, searchMap);
		return ResponseUtil.getObject(list);
	}

	/**
	 * 查看人列表
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/viewuser", method = RequestMethod.GET)
	public Object viewUserList(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		@SuppressWarnings("unchecked")
		Map<String, Object> searchMap = (Map<String, Object>) paramObject
				.get("searchMap");
		if (searchMap == null) {
			searchMap = new HashMap<String, Object>();
		}
		Map<String, Object> list = service.getViewUserList(id, searchMap);
		return ResponseUtil.getObject(list);
	}

	/**
	 * 参照列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "ref", method = RequestMethod.GET)
	public Object getRefList(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		if (paramObj != null) {
			// 有分页信息返回分页列表
			if (paramObj.containsKey(HttpKeyConstant.Page)&& paramObj.containsKey(HttpKeyConstant.PageSize)) {
				return ResponseUtil.getObject(service.getRefPage(getRequestPage(paramObj), null));
			}
		}
		List<CustomerVO> voList = service.getRefList(null);
		Page<CustomerVO> page = new Page<CustomerVO>();
		page.setData(voList);
		return ResponseUtil.getObject(page);
	}

	/**
	 * 获取分页信息
	 * @param paramObj
	 * @return
	 * @throws CrmMessageException
	 */
	private Page<CustomerVO> getRequestPage(JSONObject paramObj)
			throws CrmMessageException {
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		if (page == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		return new Page<CustomerVO>(page, pageSize);
	}

	/**
	 * 获取客户相关
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "rel", method = RequestMethod.GET)
	public Object getRelList(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObject = RequestUtil.getParamObject(request);
		Integer page = paramObject.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObject.getInt(HttpKeyConstant.PageSize);
		if (page == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		Map<String, Object> searchMap = (Map<String, Object>) paramObject.get("searchMap");

		Long cumId = Long.parseLong(searchMap.get("cumId").toString());
		List<Map<String, Object>> relList = new ArrayList<Map<String, Object>>();

		// 联系人
		Map<String, Object> contactMap = new HashMap<String, Object>();
		Map<String, Object> contactSearchMap = new HashMap<String, Object>();
		contactSearchMap.put("customer", cumId);
		Page<ContactVO> contactPage = contactRmService.getList(
				new Page<ContactVO>(page, pageSize), contactSearchMap);
		contactMap.put("title", "联系人");
		contactMap.put("list", contactPage);
		contactMap.put("action", "新增,关系图");
		relList.add(contactMap);

		// 商机
		Map<String, Object> opportunityMap = new HashMap<String, Object>();
		Map<String, Object> opportunitySearchMap = new HashMap<String, Object>();
		opportunitySearchMap.put("customerId", cumId);
		Page<OpportunityVO> opportunityPage = opportunityRmService.getList(
				new Page<OpportunityVO>(page, pageSize), opportunitySearchMap);
		opportunityMap.put("title", "商机");
		opportunityMap.put("list", opportunityPage);
		opportunityMap.put("action", "新增");
		relList.add(opportunityMap);
		
		// 文件
		Map<String, Object> fileMap = new HashMap<String, Object>();
		fileMap.put("title", "文件");
		fileMap.put("action", "上传");
		Map<String, Object> fileParam = new HashMap<String, Object>();
		fileParam.put("objType", ObjTypeEnum.CUSTOMER.getValue());
		fileParam.put("objId", cumId);
		List<AttachmentVO> attachmentList = attachService.getList(fileParam);
		Map<String,Object> fileDataMap = new HashMap<String,Object>();
		fileDataMap.put("data", attachmentList);
		fileMap.put("list", fileDataMap);
		relList.add(fileMap);
		
		JSONObject result = new JSONObject();
		result.put("data", relList);
		return ResponseUtil.getObject(result);
	}
	
	@RequestMapping(value = "verification", method = RequestMethod.GET)
	public Object checkVerifyNameExist(HttpServletRequest request, HttpServletResponse response) {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String verName = (String) paramObj.get("verifyFullname");
		boolean flag = service.checkVerifyNameExist(null, verName);
		String msg = "";
		if(flag){
			msg = "当前认证的企业信息已存在，请重新选择企业信息";
		}
		return ResponseUtil.getObject(msg);
	}
	
	/**
	 * 批量分配
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "allocation", method = RequestMethod.PUT)
	public Object batchAllocation(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String orgIdStr = paramObj.getString("orgIds");
		String cumIdStr = paramObj.getString("cumIds");
		salesRmService.batchAllocation(orgIdStr, cumIdStr);
		return ResponseUtil.getObject("分配成功");
	}
	
	/**
	 * 批量收回
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "resume", method = RequestMethod.PUT)
	public Object batchResume(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String orgIdStr = paramObj.getString("orgIds");
		String cumIdStr = paramObj.getString("cumIds");
		salesRmService.batchResume(orgIdStr, cumIdStr);
		return ResponseUtil.getObject("收回成功");
	}
	
	/**
	 * 查询已分配的销售组织
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "existorg", method = RequestMethod.GET)
	public Object getExistOrg(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String cumIdStr = paramObj.getString("cumIds");
		List<CustomerSalesVO> list = salesRmService.getExistOrg(cumIdStr);
		JSONObject result = new JSONObject();
		result.put("data", list);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 客户业务对象动态
	 * @param cumId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/dynamic", method = RequestMethod.GET)
	public Object getCumDynamic(@PathVariable("id") Long id,HttpServletRequest request, 
			HttpServletResponse response) {
		DynamicVO[] dyms = service.getCumDynamic(id);
		return ResponseUtil.getObject(transDymList2Json(dyms));
	}
	
	/**
	 * 将返回结果包装
	 * @param dymArr
	 * @return
	 */
	private JSONObject transDymList2Json(DynamicVO[] dymArr){
		JSONObject result = new JSONObject();
		if(dymArr == null || dymArr.length == 0) return result;
		List<Map<String, Object>> dynamiclist = new ArrayList<Map<String,Object>>();
		for(DynamicVO vo : dymArr){
			Map<String, Object> voMap = new HashMap<String, Object>();
			voMap.put("id", vo.getId());
			voMap.put("type", vo.getType());
			voMap.put("time", vo.getFormatTime());
			voMap.put("name", vo.getOwnerName());
			voMap.put("userid", vo.getOwnerId());
			voMap.put("content", vo.getContent());
			dynamiclist.add(voMap);
		}
		result.put("dynamiclist", dynamiclist);
		return result;
	}
}
